#include <QDebug>
#include <unistd.h>
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    comOpenStatus = false;
    for(int i = 0; i < RELAY_COUNT; i++) {
        sw[i] = false;
    }
    /**** Init Data *********/
    sendData[0] = 0xA0;
    sendData[1] = 0x01; // switch channel
    sendData[2] = 0x00; // default off
    sendData[3] = sendData[0] | (sendData[1] + sendData[2]);
    /************************/

    on_pushButton_GetCom_clicked();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::syncSwitchDataToCom(char channel, char status)
{
    qDebug("%s channel:0x%x status:0x%x", __func__, channel, status);
    char sendData[4] = {0};
    sendData[0] = 0xA0;
    sendData[1] = channel;
    sendData[2] = status;
    sendData[3] = sendData[0] | (sendData[1] + sendData[2]);
    qDebug("Hex: %X %X %X %X", sendData[0], sendData[1], sendData[2], sendData[3]);
    int writed = serialPort.write(sendData, sizeof(sendData));
    if(writed > 0) {
        qDebug("%s Command Send to Succeed. writed:%d", __func__, writed);
    } else {
        qDebug("%s Command Send Fail", __func__);
    }
}

void MainWindow::on_pushButton_GetCom_clicked()
{
    qDebug("%s", __func__);
    ui->comboBox_Com->clear();
    // 通过QSerialProtInfo查找可用串口
    foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
        ui->comboBox_Com->addItem(info.portName());
    }
}


void MainWindow::on_pushButton_OpenCom_clicked()
{
    qDebug("%s", __func__);
    qint32 baudrate;
    QSerialPort::DataBits databit;
    QSerialPort::StopBits stopbit;
    QSerialPort::Parity   parity;

    //baudrate
    baudrate = (int)ui->comboBox_Baudrate->currentText().toInt();

    //databit
    int databit_int = ui->comboBox_Digitbit->currentText().toInt();
    // qDebug("%s databit_int=%d", __func__, databit_int);
    switch(databit_int) {
    case 5: databit = QSerialPort::Data5; break;
    case 6: databit = QSerialPort::Data6; break;
    case 7: databit = QSerialPort::Data7; break;
    case 8: databit = QSerialPort::Data8; break;
    default: qDebug("%s unknow databit_int:%d", __func__, databit_int);
    }

    //stopbit
    QString stopbit_str = ui->comboBox_Stopbit->currentText();
    if(stopbit_str == "1") {
        stopbit = QSerialPort::OneStop;
    } else if (stopbit_str == "1.5") {
        stopbit = QSerialPort::OneAndHalfStop;
    } else if (stopbit_str == "2") {
        stopbit = QSerialPort::TwoStop;
    } else {
        qDebug("%s unknow stopbit_str:%s", __func__, stopbit_str.toLatin1().data());
    }

    //odd or even bit
    QString parity_str = ui->comboBox_Paritybit->currentText();
    if(parity_str == "none") {
        parity = QSerialPort::NoParity;
    } else if (parity_str == "odd") {
        parity = QSerialPort::OddParity;
    } else if (parity_str == "even") {
        parity = QSerialPort::EvenParity;
    } else {
        qDebug("%s unknow parity_str:%s", __func__, parity_str.toLatin1().data());
    }

    // set Serial Port Config
    if (comOpenStatus == false) {
        serialPort.setPortName(ui->comboBox_Com->currentText());
        serialPort.setBaudRate(baudrate);
        serialPort.setDataBits(databit);
        serialPort.setStopBits(stopbit);
        serialPort.setParity(parity);
    }

    // Start Open Uart
    if(comOpenStatus == false) {
        if(serialPort.open(QIODevice::ReadWrite)) {
            ui->pushButton_OpenCom->setText("close");
            ui->comboBox_Com->setEnabled(false);
            comOpenStatus = true;
            /* init com command */
            qDebug("%s Open Serial Serial Succeed.", __func__);
        } else {
            qDebug("%s open serial port fail", __func__);
            QMessageBox::critical(this, "ERROR", "Failed to open the serial port.\r\n"
                                                 "1.The serial port may be occupied.\r\n"
                                                 "2.Select a correct serial port.\r\n");
        }
    } else {
        serialPort.close();
        ui->pushButton_OpenCom->setText("open");
        ui->comboBox_Com->setEnabled(true);
        comOpenStatus = false;
    }

}


void MainWindow::on_pushButton_switch1_released()
{
    qDebug("%s", __func__);
    sw[0] = !sw[0];
    syncSwitchDataToCom(0x01, sw[0] ? 0x01 : 0x00);
    ui->pushButton_switch1->setText(sw[0]?"OFF":"ON");
}


void MainWindow::on_pushButton_switch2_released()
{
    qDebug("%s", __func__);
    sw[1] = !sw[1];
    syncSwitchDataToCom(0x02, sw[1] ? 0x01 : 0x00);
    ui->pushButton_switch2->setText(sw[1]?"OFF":"ON");
}


void MainWindow::on_pushButton_switch3_released()
{
    qDebug("%s", __func__);
    sw[2] = !sw[2];
    syncSwitchDataToCom(0x03, sw[2] ? 0x01 : 0x00);
    ui->pushButton_switch3->setText(sw[2]?"OFF":"ON");
}


void MainWindow::on_pushButton_switch4_released()
{
    qDebug("%s", __func__);
    sw[3] = !sw[3];
    syncSwitchDataToCom(0x04, sw[3] ? 0x01 : 0x00);
    ui->pushButton_switch4->setText(sw[3]?"OFF":"ON");
}

